const { table } = require('console');
var express = require('express');
var router = express.Router();
var fs = require('fs');

function getPathByMap(tableName) {
  let folderPath = 'F:/app-report-boot/src/report-instance/' + tableName;
  return folderPath;
}

//查询所有，必选参数：tableName,可选参数：filter
router.post('/:tableName', function (req, res) {
  let tableName = req.params.tableName;
  const folderPath = getPathByMap(tableName);

  const fileName = req.body.common.name;
  fs.writeFileSync(folderPath + '/' + fileName + '.json', JSON.stringify(req.body, null, 2));

  res.send({
    code: 200,
    message: '成功',
    src: 'express',
    data: fileName
  });
});

//查询所有，必选参数：tableName,可选参数：filter
router.put('/:tableName', function (req, res) {
  let tableName = req.params.tableName;
  const folderPath = getPathByMap(tableName);

  const fileName = req.body.common.name;
  fs.writeFileSync(folderPath + '/' + fileName + '.json', JSON.stringify(req.body, null, 2));

  res.send({
    code: 200,
    message: '成功',
    src: 'express',
    data: fileName
  });
});

//查询所有，必选参数：tableName,可选参数：filter
router.delete('/:tableName', function (req, res) {
  let tableName = req.params.tableName;
  const folderPath = getPathByMap(tableName);

  const fileName = req.query.name;
  fs.unlinkSync(folderPath + '/' + fileName + '.json', JSON.stringify(req.body, null, 2));

  res.send({
    code: 200,
    message: '成功',
    src: 'express',
    data: fileName
  });
});

//查询所有，必选参数：tableName,可选参数：filter
router.get('/:tableName', function (req, res) {
  let tableName = req.params.tableName;
  const folderPath = getPathByMap(tableName);

  // 查询单个
  if (req.query && req.query.name) {
    const fileStr = fs.readFileSync(folderPath + '/' + req.query.name + '.json', { encoding: 'utf8' });
    const metaObj = JSON.parse(fileStr);
    res.send({
      code: 200,
      message: '成功',
      src: 'express',
      data: metaObj
    });
    return;
  }

  // 查询列表，读取文件
  const nameList = fs.readdirSync(folderPath);
  const retList = [];
  nameList.forEach(fileName => {
    const fileStr = fs.readFileSync(folderPath + '/' + fileName, { encoding: 'utf8' });
    const metaObj = JSON.parse(fileStr);
    retList.push(metaObj);
  });

  res.send({
    code: 200,
    message: '成功',
    src: 'express',
    data: {
      content: retList
    }
  });
});

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;